package net.freebytes.ssmp.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.freebytes.ssmp.entity.User;
import net.freebytes.ssmp.util.RespBean;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 登录管理
 *
 * @author 千里明月
 * @date 2021/7/20
 **/
@Api(tags = "登录管理")
@Controller
@RequestMapping("/rest/ssmp")
public class LoginController {


    @ApiOperation(value = "登录接口")
    @PostMapping("/login")
    @ResponseBody
    public RespBean login(@RequestBody User user) {
        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            return RespBean.uncertified("账号密码不能为空");
        }
        //用户认证信息
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        try {
            //进行验证，这里可以捕获异常，然后返回对应信息
            Subject subject = SecurityUtils.getSubject();
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException e) {
            return RespBean.uncertified("用户名不存在");
        } catch (AuthenticationException e) {
            return RespBean.uncertified("账号或密码错误");
        } catch (AuthorizationException e) {
            return RespBean.uncertified("没有权限");
        }
        return RespBean.ok("success");
    }

}